var app = require('http').createServer()
var io = require('socket.io')(app)

var PORT = 3000

// 客户端计数
var clinetCount = 0

// 用来存储客户端 socket
var socketMap = {}

app.listen(PORT)

var bindListener = function(socket, event) {
  socket.on(event, function(data) {
    if (socket.clientNum % 2 === 0) {
      if (socketMap[socket.clientNum - 1]) {
        socketMap[socket.clientNum - 1].emit(event, data)
      }
    } else {
      if (socketMap[socket.clientNum + 1]) {
        socketMap[socket.clientNum + 1].emit(event, data)
      }
    }
  })
}

io.on('connection', function(socket) {
  clinetCount = clinetCount + 1
  socket.clientNum = clinetCount
  socketMap[clinetCount] = socket

  if (clinetCount % 2 === 1) {
    socket.emit('waiting', '等待中。。。')
  } else {
    if (socketMap[(clinetCount - 1)]) {
      socket.emit('start')
      socketMap[(clinetCount - 1)].emit('start')
    } else {
      socket.emit('leave')
    }
  }

  bindListener(socket, 'init')
  bindListener(socket, 'next')
  bindListener(socket, 'rotate')
  bindListener(socket, 'right')
  bindListener(socket, 'down')
  bindListener(socket, 'left')
  bindListener(socket, 'fall')
  bindListener(socket, 'fixed')
  bindListener(socket, 'line')
  bindListener(socket, 'time')
  bindListener(socket, 'lose')
  bindListener(socket, 'bottomLines')
  bindListener(socket, 'addTaiLines')

  socket.on('disconnect', function() {
    if (socket.clientNum % 2 === 0) {
      if (socketMap[socket.clientNum - 1]) {
        socketMap[socket.clientNum - 1].emit('leave')
      }
    } else {
      if (socketMap[socket.clientNum + 1]) {
        socketMap[socket.clientNum + 1].emit('leave')
      }
    }
    delete(socketMap[socket.clientNum])
  })
})

console.log(`webSocket server listening on port: ${PORT}`)